import "dotenv/config";
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage } from "@langchain/core/messages";
import {
  StructuredOutputParser,
  CommaSeparatedListOutputParser,
  OutputParserException,
  JsonOutputParser,
} from "@langchain/core/output_parsers";
import { PromptTemplate } from "@langchain/core/prompts";
import { z } from "zod";
import { OutputFixingParser } from "langchain/output_parsers";

const schema = z.object({
  answer: z.string().describe("用户问题的答案"),
  confidence: z.number().min(0).max(100).describe("问题答案的可信度评分，满分 100"),
});

// const model = new ChatOpenAI({
//   configuration: {
//     baseURL: process.env.OPENAI_API_BASE,
//     apiKey: process.env.OPENAI_API_KEY,
//   },
// });

// const joke = await model.invoke([new HumanMessage("讲个笑话吧")]);

// console.log(joke);

StructuredOutputParser.fromNamesAndDescriptions({
  question: "用户的问题",
  answer: "用户问题的答案",
  evidence: "你回答用户问题所依据的答案",
  confidence: "问题答案的可信度评分，格式是百分数",
  tokens: "回答所使用的token数量",
});

const parser = StructuredOutputParser.fromZodSchema(schema);

const commaParser = new CommaSeparatedListOutputParser();
// console.log(parser.getFormatInstructions());

const prompt = PromptTemplate.fromTemplate("尽可能的回答用的问题 \n{instructions} \n{question}");
// const prompt = PromptTemplate.fromTemplate("列出3个 {country} 的著名的互联网公司.\n{instructions}");
const model = new ChatOpenAI({
  configuration: {
    baseURL: process.env.OPENAI_API_BASE,
    apiKey: process.env.OPENAI_API_KEY,
  },
});

// const chain = prompt.pipe(model).pipe(parser);
// const res = await chain.invoke({
//   question: "蒙娜丽莎的作者是谁？是什么时候绘制的",
//   instructions: parser.getFormatInstructions(),
//   //   country: "美国",
//   //   instructions: commaParser.getFormatInstructions(),
// });

// console.log(res);

const wrongOutput = {
  answer: "蒙娜丽莎的作者是达芬奇，大约在16世纪初期（1503年至1506年之间）开始绘制。",
  sources: "90%",
};

const fixParser = OutputFixingParser.fromLLM(model, parser);
const output = await fixParser.parse(JSON.stringify(wrongOutput));
console.log(output);
